package org.zhss.demo.redis.hyperloglog;

import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/** 网站日常指标统计案例 */
public class WebSiteStatisticsDemo {

  private Jedis jedis = new Jedis("192.168.150.201");

  /** 初始化某一天的uv数据 */
  public void initUVdata(String date) {
    int startIndex = new Random().nextInt(1000);
    System.out.println("今天访问uv起始id为：" + startIndex);

    for (int i = startIndex; i < startIndex + 1358; i++) {
      for (int j = 0; j < 10; j++) {
        jedis.pfadd("hyperloglog_uv_" + date, String.valueOf(i + 1));
      }
    }
  }

  /**
   * 获取UV值
   *
   * @param data
   * @return
   */
  public long getUV(String data) {
    return jedis.pfcount("hyperloglog_uv_" + data);
  }

  /**
   * 获取周UV值
   *
   * @return
   */
  public long getWeeklyUV() {
    ArrayList<String> keys = new ArrayList<>();

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());

    for (int i = 0; i < 7; i++) {
      calendar.add(Calendar.HOUR_OF_DAY, 1);
      String date = dateFormat.format(calendar.getTime());
      keys.add("hyperloglog_uv_" + date);
    }
    String[] keyArray = keys.toArray(new String[keys.size()]);
    jedis.pfmerge("weekly_uv", keyArray);

    return jedis.pfcount("weekly_uv");
  }

  public static void main(String[] args) {
    WebSiteStatisticsDemo demo = new WebSiteStatisticsDemo();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());

    long duplicateUv = 0;

    for (int i = 0; i < 7; i++) {
      calendar.add(Calendar.HOUR_OF_DAY, 1);
      String date = dateFormat.format(calendar.getTime());
      demo.initUVdata(date);

      long uv = demo.getUV(date);

      duplicateUv += uv;
      System.out.println("日期为：" + date + "，的uv值为：" + duplicateUv);
    }

    long weeklyUV = demo.getWeeklyUV();
    System.out.println("实际的周活跃用户数为：" + weeklyUV);
  }
}
